{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Functions" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Function definitions\n", "All functions start with **def**, which states we are defining a function. This is followed by the function name, and cap it off with a **():**\n", "\n", "Function name formatting:\n", " - All lower case\n", " - Underscores to seperate words\n", " \n", "Example:\n", " - **def sample_function():**" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "def print_hello_world():\n", " \"\"\"This defines a function, proper commenting dictates that we state the fucntion (printing hello) in this section\n", " Additional comments (args, return values, etc) can be made in the following lines\n", " \"\"\"\n", " # Using the print command we can send ouptut to the console\n", " print(\"hello world\")\n", "\n", "# After defining our function we can invoke it simply by calling the function name\n", "# Note: Must define a function in code before calling it, otherwise we run into the error seen below\n", "print_hello_world()\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "#if we fail to define a function before invoking it\n", "\n", "print(\"**********\\nCalling Undefined Functions:\")\n", "print_hello()\n", "\n", "def print_hello():\n", " \"\"\"Print hello out to console\"\"\"\n", " print(\"hello\")\n", " " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Returning Values\n", "To return values form a function, we simply need to state **return {object}**. While you can encase the object you are returning with a (), this is not standard or required." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "#Returning values\n", "def return_hello():\n", " \"\"\"Return 'hello' out to console\n", " Returns:\n", " str - 'hello'\n", " \"\"\"\n", " return \"hello\" #The return() method tells the function what to return\n", "\n", "h = return_hello()\n", "print(h)\n", "\n", "#NOTE - python does not decalare a return type! This means you are able to return whatever you want\n", "# this can be a gift and a curse. What do you think I mean by that?" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Parameters - By Reference vs. Value\n", "Parameters in python are defined by a comma-separated list of parameter names.\n", " - def sample_function**({param_name_1}, {param_name_2}, ...)**:\n", "\n", "Python passes mutable objects by reference and immutables as values\n", "Common Immutables:\n", " - numeric types (int, float, decimal, complex)\n", " - strings\n", " - tuples\n", " - bool" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "\n", "def append_to_list(lst, b):\n", " \"\"\"appends a value to a list\n", " Args:\n", " lst (list) - generic list of values\n", " b - object to append to lst\n", " \"\"\"\n", " # After the function name we can list parameters/inputs needed\n", " # If the object is immutable it is passed by reference - Explanation!\n", " lst.append(b)\n", " b + 6\n", " \n", "test_lst = [1,2,3,4]\n", "b = 5\n", "append_to_list(test_lst, b)\n", "print(\"lst = {} and b = {}\".format(test_lst, b))\n", "\n", "# QUESTION - What do you think will be the result?\n", "\n", "# QUESTION - Why can this be dangerous when programming?" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We can also define default values for parameters by putting in **{param_name} = {default_value}**." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "\n", "def power(a, exp = 2):\n", " \"\"\"generates a**exp\n", " Args:\n", " a (int/float) - base of x^y\n", " exp (int) - exp of x^y\n", " Returns:\n", " int - a to the power of exp\n", " \"\"\"\n", " #following a parameter with the '=' and a value defines a default value for that parameter\n", " base = a #Remember ints are immutable\n", " while exp > 1:\n", " a *= base\n", " exp -= 1\n", " return(a)\n", "\n", "print(power(3,3))\n", "print(power(4)) # What will this return?\n" ] }, { "cell_type": "markdown", "metadata": { "collapsed": true }, "source": [ "### In class work" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "#Problem 1\n", "\"\"\"\n", "Write a function that will take two lists (lst1 and lst2), contianing strings and ints, and returns\n", "a singluar list of ints (including any strings that can be represented as ints: Ex. \"5\" -> 5)\n", " - Hint1: int(\"5\") -> 5\n", " - Hint2: You'll probably want to use a try except statement in your function\n", " \n", "Ex. lst1 = [1,'hello',34,'-23'], lst2 = [54,'23','bye',3] -> [1,34,-23,54,23,3]\n", "\"\"\"\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Functions as first class objects\n", "First class objects means that all python functions can be treated exactly the same way as any other object. This means they can:\n", " - Be passed as parameters\n", " - Assigned to variables\n", " - Aggregated into lists/dictionaries\n", " - Etc." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "\n", "print(\"**********\\nFunctions as Arguments:\")\n", "def addition(x, y):\n", " \"\"\"Adds two values together\n", " Args:\n", " x (numeric)\n", " y (numeric)\n", " \n", " Returns:\n", " x + y\n", " \"\"\"\n", " return(x+y)\n", "\n", "def apply_func(func, x, y):\n", " \"\"\"Pass two values to provided function\n", " Args:\n", " func (function) - function that takes two args\n", " x - value\n", " y - value\n", " \n", " Returns:\n", " Result of func(x,y)\n", " \"\"\"\n", " return(func(x, y))\n", "\n", "a = 3\n", "b = 38\n", "\n", "result = apply_func(addition, a, b)\n", "print(result)\n" ] }, { "cell_type": "markdown", "metadata": { "collapsed": true }, "source": [ "### In class work" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "#Problem 1\n", "\"\"\"\n", "Create another function that can be integrated with apply_func\n", "\"\"\"\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(\"**********\\nApplication for First Class Functions:\")\n", "def square(x):\n", " \"\"\"Rasie arg to power of 2\n", " Args:\n", " x (numeric) - value\n", " \n", " Returns:\n", " x to the power of 2\n", " \"\"\"\n", " return(x**2)\n", "\n", "lst = [1,2,3,4]\n", "print(list(map(square, lst))) # This allows us to do cool things like map functions onto lists\n", "# the map() function simply applies a function to all elements of an iterable (ele in lst)\n", "\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Anonymous/Lambda functions" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(\"**********\\nLambda Functions:\")\n", "# lambda expressions are anonymous functions, but not quite functional programming lambdas\n", "plus2 = lambda x: x + 2\n", "print(plus2(4))\n", "\n", "# lambda's are great for inline function calls\n", "lst_map = map(lambda x,y: x*y-y, [1,2,3,4,5,6], [2,4,6,8,10,12])\n", "print(list(lst_map))" ] }, { "cell_type": "markdown", "metadata": { "collapsed": true }, "source": [ "### In class work" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "#Problem 1\n", "\"\"\"\n", "Use a lambda (with map()) expression to create a list of bools that states\n", "whether or not the elements in lst1 are greater than the elements in lst2\n", "\n", "Ex. lst1 = [1,2,3,4,5], lst2 = [5,4,3,2,1] would return [False, False, False, True]\n", "\"\"\"\n", "lst1 = [1,2,3,4,5]\n", "lst2 = [5,4,3,2,1]\n" ] } ], "metadata": { "kernelspec": { "display_name": "Python [default]", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.6.6" } }, "nbformat": 4, "nbformat_minor": 2 }